package com.hw.one.dam2.service;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.hw.one.core.service.BaseService;
import com.hw.one.dam2.common.DamConstant;
import com.hw.one.dam2.config.DamConfig;
import com.hw.one.dam2.dao.ISourceDataDao;
import com.hw.one.dam2.param.SmallAirParam;
import com.hw.one.dam2.util.HttpClientUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Copyright 2017 汉威.智慧环保事业部.
 * Created by 李亚坤 on 2017/07/11 10:09.
 */
@Service
public class QuartzService extends BaseService implements IQuartzService {

    private static final DamConfig damConfig = DamConfig.getInstance();

    private static String xdmlGpoint = damConfig.get("GPOINT_XDML");
    private static String xdmlSmall_led = damConfig.get("SMALL_XDML");
    private static String xdmlSmall2 = damConfig.get("SMALL_XDML2");
    private static String hjyKey = damConfig.get("HJY_KEY");
    private static String gpointCode = damConfig.get("GPOINT_XDML_CODE");
    private static double gpointPm10 = Double.parseDouble(damConfig.get("PERCENT_PM10"));
    private static double gpointPm25 = Double.parseDouble(damConfig.get("PERCENT_PM2_5"));
    private static double gpointSo2 = Double.parseDouble(damConfig.get("PERCENT_SO2"));
    private static double gpointNo2 = Double.parseDouble(damConfig.get("PERCENT_NO2"));
    private static double gpointCo = Double.parseDouble(damConfig.get("PERCENT_CO"));
    private static double gpointO3 = Double.parseDouble(damConfig.get("PERCENT_O3"));

    private static String lastMonitorTime;
    private static String lastMonitorTime2;

    @Autowired
    private ISourceDataDao sourceDataDao;

    @SuppressWarnings("unchecked")
    @Override
    public void saveScreenDataPullData() throws Exception {

//		Map aqiInfoMap = smallAirDao.findSmallAirNewMinuteOneDataBySiteCode(siteCode);
        Map smallData = sourceDataDao.findScCollectMin5NewMinuteOneDataBySnCode(xdmlSmall_led);
        String monitorTime = (String) smallData.get("MONITORTIME");
        SimpleDateFormat sdf = new SimpleDateFormat(DamConstant.SDF_YMD_HMS);
        if (null == lastMonitorTime) {
            lastMonitorTime = monitorTime;
        } else if (sdf.parse(monitorTime).getTime() - sdf.parse(lastMonitorTime).getTime() > 0) {
            log.debug("-------------数据已经更新(" + xdmlSmall_led + ")----上次更新时间:" + lastMonitorTime + "  此次更新时间:" + monitorTime);
            lastMonitorTime = monitorTime;
            dealDataAndSave(smallData);
        } else {
            log.debug("-------------数据未更新(" + xdmlSmall_led + ")----上次更新时间:" + lastMonitorTime + "  此次更新时间:" + monitorTime);
        }

        Map smallData2 = sourceDataDao.findScCollectMin5NewMinuteOneDataBySnCode(xdmlSmall2);
        String monitorTime2 = (String) smallData2.get("MONITORTIME");
        if (null == lastMonitorTime2) {
            lastMonitorTime2 = monitorTime2;
        } else if (sdf.parse(monitorTime2).getTime() - sdf.parse(lastMonitorTime2).getTime() > 0) {
            log.debug("-------------数据已经更新(" + xdmlSmall2 + ")----上次更新时间:" + lastMonitorTime2 + "  此次更新时间:" + monitorTime2);
            lastMonitorTime2 = monitorTime2;
            dealDataAndSave(smallData2);
        } else {
            log.debug("-------------数据未更新(" + xdmlSmall2 + ")----上次更新时间:" + lastMonitorTime2 + "  此次更新时间:" + monitorTime2);
        }


    }

    /**
     * 处理并保存数据
     *
     * @param smallData
     */
    private void dealDataAndSave(Map smallData) {
        String monitorTime = (String) smallData.get("MONITORTIME");
        String snCode = (String) smallData.get("SNCODE");
        Map<String, Object> smallMonitorData = (Map<String, Object>) smallData.get("MONITORDATA");
        Integer smallPm10 = smallMonitorData.get("CTPM10") == null ? 0 : (Integer) smallMonitorData.get("CTPM10");
        Integer smallPm25 = smallMonitorData.get("CTPM25") == null ? 0 : (Integer) smallMonitorData.get("CTPM25");
        Integer smallSo2 = smallMonitorData.get("CTSO2") == null ? 0 : (Integer) smallMonitorData.get("CTSO2");
        Integer smallNo2 = smallMonitorData.get("CTNO2") == null ? 0 : (Integer) smallMonitorData.get("CTNO2");
        Integer smallCo = smallMonitorData.get("CTCO") == null ? 0 : (Integer) smallMonitorData.get("CTCO");
        Integer smallO3 = smallMonitorData.get("CTO3") == null ? 0 : (Integer) smallMonitorData.get("CTO3");
        Double smallTemp = smallMonitorData.get("TEMP") == null ? 0.0 : (Double) smallMonitorData.get("TEMP");
        Double smallHum = smallMonitorData.get("HUM") == null ? 0.0 : (Double) smallMonitorData.get("HUM");
        // 请求环境云数据
        String httpUrl = "http://service.envicloud.cn:8082/v2/air/live/device/" + hjyKey + "/" + gpointCode;
        Map<String, String> httpResultMap = HttpClientUtil.sendGet(httpUrl, new HashMap<>());
        JSONObject infoObj = new JSONObject();
        if ("200".equals(httpResultMap.get("statusCode"))) {
            JSONObject resultObj = JSONObject.parseObject(httpResultMap.get("result"));
            if ("Success".equals(resultObj.get("rdesc"))) {
                infoObj = resultObj.getJSONObject("info");
                System.out.println("PM10 = " + infoObj.get("PM10"));
                System.out.println("PM25 = " + infoObj.get("PM25"));
                System.out.println("SO2 = " + infoObj.get("SO2"));
                System.out.println("NO2 = " + infoObj.get("NO2"));
                System.out.println("CO = " + infoObj.get("CO"));
                System.out.println("o3 = " + infoObj.get("o3"));
                System.out.println("AQI = " + infoObj.get("AQI"));
                System.out.println("prkey = " + infoObj.get("prkey"));
            } else {
                return;
            }
        } else {
            return;
        }
        int pm25 = infoObj.getInteger("PM25") == null ? 0 : infoObj.getIntValue("PM25");
        int pm10 = infoObj.getString("PM10") == null ? 0 : infoObj.getIntValue("PM10");
        int so2 = infoObj.getString("SO2") == null ? 0 : infoObj.getIntValue("SO2");
        int no2 = infoObj.getString("NO2") == null ? 0 : infoObj.getIntValue("NO2");
        int o3 = infoObj.getString("o3") == null ? 0 : infoObj.getIntValue("o3");
        double co = infoObj.getString("CO") == null ? 0 : infoObj.getDoubleValue("CO");
        log.debug("-------------------计算西大明路数据,前查询环境云国控数据(" + gpointCode + ")-----------------------");
        log.debug("PM10:" + pm10 + " |PM2.5:" + pm25 + "|SO2:" + so2 + "|NO2:" + no2 + "|O3:" + o3 + "|CO:" + co);
        log.debug("--------------------------------------------------------------------");

        DecimalFormat df_3 = new DecimalFormat("###.###");
        DecimalFormat df = new DecimalFormat("#######");
        int resultPm10 = 0;
        int resultPm25 = 0;
        int resultSo2 = 0;
        int resultNo2 = 0;
        double resultCo = 0.0;
        int resultO3 = 0;
        if(smallPm10 <= 0) {
            log.debug("--------------小型站数据PM10小于等于0,跳过【"+smallPm10+"】");
            resultPm10 = pm10;
        }else {
            resultPm10 = Integer.parseInt(df.format(pm10 * gpointPm10 + (1 - gpointPm10) * smallPm10));
        }
        if(smallPm25 <= 0) {
            log.debug("--------------小型站数据PM25小于等于0,跳过【"+smallPm25+"】");
            resultPm25 = pm25;
        }else {
            resultPm25 = Integer.parseInt(df.format(pm25 * gpointPm25 + (1 - gpointPm25) * smallPm25));
        }
        if(smallSo2 <= 0) {
            log.debug("--------------小型站数据SO2小于等于0,跳过【"+smallSo2+"】");
            resultSo2 = so2;
        }else {
            resultSo2 = Integer.parseInt(df.format(so2 * gpointSo2 + (1 - gpointSo2) * smallSo2));
        }
        if(smallNo2 <= 0) {
            log.debug("--------------小型站数据NO2小于等于0,跳过【"+smallNo2+"】");
            resultNo2 = no2;
        }else {
            resultNo2 = Integer.parseInt(df.format(no2 * gpointNo2 + (1 - gpointNo2) * smallNo2));
        }
        if(smallCo <= 0) {
            log.debug("--------------小型站数据CO小于等于0,跳过【"+smallCo+"】");
            resultCo = co;
        }else {
            resultCo = Double.parseDouble(df_3.format(co * gpointCo + (1 - gpointCo) * (smallCo / 1000)));
        }
        if(smallO3 <= 0) {
            log.debug("--------------小型站数据O3小于等于0,跳过【"+smallO3+"】");
            resultO3 = o3;
        }else {
            resultO3 = Integer.parseInt(df.format(o3 * gpointO3 + (1 - gpointO3) * smallO3));
        }

//		co = Double.valueOf(decimalFormat.format(co));
        log.debug("-------------------计算西大明路数据,校准后数据-----------------------" + monitorTime);
        log.debug("PM10:" + resultPm10 + " |PM2.5:" + resultPm25 + "|SO2:" + resultSo2 + "|NO2:" + resultNo2 + "|O3:" + resultO3 + "|CO:" + resultCo + "|TEMP:" + smallTemp + "|HUM:" + smallHum);
        log.debug("--------------------------------------------------------------------");

        SimpleDateFormat sdf = new SimpleDateFormat(DamConstant.SDF_YMD_HMS);
        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("SNCODE", snCode);
        resultMap.put("MONITORCODE", smallData.get("MONITORCODE"));
        resultMap.put("MONITORTIME", monitorTime);
        resultMap.put("CREATETIME", sdf.format(new Date()));
        resultMap.put("PM10", resultPm10);
        resultMap.put("PM25", resultPm25);
        resultMap.put("SO2", resultSo2);
        resultMap.put("NO2", resultNo2);
        resultMap.put("CO", resultCo);
        resultMap.put("O3", resultO3);
        resultMap.put("TEMP", smallTemp);
        resultMap.put("HUM", smallHum);
        log.debug("--------------------开始保存计算的推送数据--------------");
        sourceDataDao.insertScreenDataData(resultMap);
        log.debug("--------------------保存成功----------------------------");
    }



    @Override
    public Map<String, Object> findScreenData(SmallAirParam smallAirParam) {

        JSONArray monitorTimeList = new JSONArray();
        JSONArray pm10List = new JSONArray();
        JSONArray pm25List = new JSONArray();
        JSONArray so2List = new JSONArray();
        JSONArray no2List = new JSONArray();
        JSONArray coList = new JSONArray();
        JSONArray o3List = new JSONArray();
        JSONArray tempList = new JSONArray();
        JSONArray humList = new JSONArray();
        List<Map> screenDataList = sourceDataDao.findScreenDataDataBySNCodeListAndTime(smallAirParam);
        for (Map monitorData : screenDataList) {
            pm10List.add(monitorData.get("PM10"));
            pm25List.add(monitorData.get("PM25"));
            so2List.add(monitorData.get("SO2"));
            no2List.add(monitorData.get("NO2"));
            coList.add(monitorData.get("CO"));
            o3List.add(monitorData.get("O3"));
            tempList.add(monitorData.get("TEMP"));
            humList.add(monitorData.get("HUM"));
            monitorTimeList.add(monitorData.get("MONITORTIME"));
        }
        JSONArray dataList = new JSONArray();
        JSONArray factorName = new JSONArray();
        factorName.add("PM10");
        factorName.add("PM2.5");
        factorName.add("SO2");
        factorName.add("NO2");
        factorName.add("CO");
        factorName.add("O3");
        factorName.add("温度");
        factorName.add("湿度");
        dataList.add(pm10List);
        dataList.add(pm25List);
        dataList.add(so2List);
        dataList.add(no2List);
        dataList.add(coList);
        dataList.add(o3List);
        dataList.add(tempList);
        dataList.add(humList);
        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("timeList", monitorTimeList);
        resultMap.put("factorList", factorName);
        resultMap.put("dataList", dataList);
        return resultMap;
    }

    @Override
    public List<Map> findScreenTableData(SmallAirParam smallAirParam) {

        List<Map> resultMapList = new ArrayList<>();
        Map<String, Object> map = null;
        int index = 1;
        List<Map> screenDataList = sourceDataDao.findScreenDataDataBySNCodeListAndTime(smallAirParam);
        for (Map monitorData : screenDataList) {
            map = new HashMap<>();
            map.put("index", index++);
            map.put("pm10", monitorData.get("PM10"));
            map.put("pm25", monitorData.get("PM25"));
            map.put("so2", monitorData.get("SO2"));
            map.put("no2", monitorData.get("NO2"));
            map.put("co", monitorData.get("CO"));
            map.put("o3", monitorData.get("O3"));
            map.put("temp", monitorData.get("TEMP"));
            map.put("hum", monitorData.get("HUM"));
            map.put("monitorTime", monitorData.get("MONITORTIME"));
            resultMapList.add(map);
        }

        return resultMapList;
    }
}
